/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fileManagers;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Victor
 */
public class HTMLController implements Serializable{
    private DocumentBuilderFactory factory;
    private DocumentBuilder docBuilder;
    private Document doc;
    private File input;
    private BufferedWriter output;
    
    public HTMLController() {
        try {
            factory = DocumentBuilderFactory.newInstance();  //Get the DocumentBuilder
            docBuilder = factory.newDocumentBuilder();       //Create blank DOM Document
            
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(HTMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

 
    public void makeForm(NodeList nl, int indentation){
        for (int i=0; i<nl.getLength(); i++)
            try {

                if (nl.item(i).getNodeName().compareTo("node")==0) {
                    for (int j=0; j<indentation; j++) output.write("     ");
                    output.write("<p>"+nl.item(i).getAttributes().item(0).getNodeValue()+"</p>\n");
                }
                if (nl.item(i).getNodeName().compareTo("field")==0){
                    for (int j=0; j<indentation; j++) output.write("\t");
                    output.write(nl.item(i).getAttributes().item(0).getNodeValue()+": <input type=\"text\"name=\""+nl.item(i).getAttributes().item(0).getNodeValue()+"\" />\n");
                }
                if (nl.item(i).hasChildNodes()) {

                    makeForm(nl.item(i).getChildNodes(), indentation+1);

                }
            }
            catch (IOException ex) {
                Logger.getLogger(HTMLController.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
    public void parseToHTML(File xml){
        try {
            input = xml;
            doc = docBuilder.parse(input);
            
            FileWriter fstream= new FileWriter("output.html");
            output = new BufferedWriter(fstream);
            
            output.write("<html>\n<body>\n<form>\n");
            makeForm(doc.getDocumentElement().getChildNodes(), 0);
            output.write("</form>\n</body>\n</html>");
            output.close();
        } catch (SAXException ex) {
            Logger.getLogger(HTMLController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HTMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
}
